package com.monolithiot.sso.controller;

import com.google.code.kaptcha.Producer;
import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.vo.BasicJsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 2018/12/14 Create by 郭文梁
 * VerifyCodeController
 * 验证码相关访问控制器
 *
 * @author 郭文梁
 * @date 2018/12/14
 */
@RestController
@RequestMapping("/verify")
public class VerifyCodeController implements ControllerSupport {
    private final Producer producer;

    @Autowired
    public VerifyCodeController(Producer producer) {
        this.producer = producer;
    }

    /**
     * 生成图片验证码并将验证码字符串放入Session
     *
     * @param request  请求对象
     * @param response 相应对象
     * @throws IOException IO异常
     */
    @GetMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = producer.createText();
            request.getSession().setAttribute(Constants.Key.SESSION_VERIFY_CODE, createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = producer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        OutputStream responseOutputStream =
                response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 验证用户输入的验证码
     *
     * @param code       用户输入的验证码
     * @param verifyCode Session中保存的验证码
     * @return BJR without data
     */
    @GetMapping("/validate")
    public BasicJsonResponse<Void> verify(String code,
                                          @SessionAttribute(Constants.Key.SESSION_VERIFY_CODE) String verifyCode) {
        return verifyCode.equalsIgnoreCase(code) ? BasicJsonResponse.ok() : BasicJsonResponse.paramError("验证码错误");
    }
}
